<template>
  <cl-dialog title="管理部门" width="700px" :visible.sync="visible" :before-close="beforeClose" @close="close" :props="{
    top: '5vh',
    closeOnClickModal: false
  }">
    <el-form ref="form" :model="form" :rules="rules" label-position="top" :disabled="saving">
      <el-form-item label="管理部门" prop="is_assign" required>
        <el-radio-group v-model="form.is_assign" @change="treeExpand">
          <el-radio :label="0">全部</el-radio>
          <el-radio :label="1">指定</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item class="bmw" prop="manage_section_ids" v-if="form.is_assign == 1" label-width="auto">
        <template #label>
          <div>
            <span style="margin-right: 15px;width: 100px;">指定部门</span>
            <el-input style="display: inline-block;" placeholder="请输入部门" v-model="searchText"></el-input>
          </div>

          <!-- -->




        </template>
        <!-- <el-checkbox-group v-model="form.manage_section_ids">
					<el-row>
						<el-col :span="8" v-for="(item, index) in deptList" :key="index">
							<el-checkbox :label="item.dept_id" name="manage_section_ids">
								{{ item.dept_name }}
							</el-checkbox>
						</el-col>
					</el-row>
				</el-checkbox-group> -->
        <el-tree :class="[browser.isMobile ? 'mobile-tree' : 'pc-tree']" ref="tree" :data="deptList"
          :default-checked-keys="form.manage_section_ids" :filter-node-method="filterNode" node-key="dept_id"
          show-checkbox highlight-current default-expand-all @check="treeCheckChange" @node-expand="treeExpand"
          :render-content="renderContent" :props="{
            value: 'dept_id',
            label: 'dept_name'
          }" />
        <input type="hidden" v-model="form.manage_dept_ids" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">关闭</el-button>
      <el-button type="primary" @click="submit" :loading="saving">确定</el-button>
    </template>
  </cl-dialog>
</template>
<script>
import { mapGetters } from "vuex";
import { addClass } from "@/utils";
export default {
  name: "manage-dept",
  data() {
    return {
      visible: false,
      form: {
        user_id: "",
        is_assign: 0, // 是否指定
        manage_section_ids: [],
        manage_section_id: "",
        manage_biz_id: "",
        manage_channel_id: "",
        manage_dept_id: ""
      },
      rules: {
        manage_section_ids: [{ required: true, message: "请选择部门" }]
      },
      saving: false,
      deptList: [],
      searchText: "",
    };
  },
  watch: {
    searchText(val) {
      this.$refs.tree.filter(val);
    }
  },
  computed: {
    ...mapGetters(["browser"])
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.dept_name.indexOf(value) !== -1;
    },
    async open(data = {}) {
      this.visible = true;
      Object.keys(this.form).forEach(key => {
        this.form[key] = data[key];
      });
      let is_assign = data.manage_section_id == "*" ? 0 : 1;
      this.form.is_assign = is_assign;

      let { is_teacher, biz_id } = data;
      await (is_teacher ? this.getShopList(biz_id) : this.getDeptList(biz_id));
      let manage_section_ids =
        is_assign == 0
          ? []
          : (data.manage_section_id || "")
            .split(",")
            .filter(Boolean)
            .map(Number);
      let check_ids = this.filterChecks(manage_section_ids);
      console.log({ check_ids });
      this.form.manage_section_ids = check_ids;
    },
    // 处理选中的数据
    filterChecks(ids) {
      const { is_assign } = this.form;
      if (is_assign == 0) return [];
      let result = [];
      let deep = (list, index = 0, parent) => {
        for (let i = 0; i < list.length; i++) {
          const item = list[i];
          let children = item?.children || [];
          deep(children, index + 1, parent);
          let check_ids = children
            .filter(v => ids.includes(v.dept_id))
            .map(v => v.dept_id);
          result.push(...check_ids);
          if (index == 0 && ids.includes(item.dept_id) && !check_ids.length) {
            result.push(item.dept_id);
          }
          if (parent && check_ids.length == children.length) {
            result.push(parent.dept_id);
          }
        }
      };
      deep(this.deptList, 0);
      return result;
    },
    beforeClose(done) {
      if (this.saving) return;
      done();
    },
    close() {
      if (this.saving) return;
      this.visible = false;
      this.reset();
    },
    reset() {
      this.saving = false;
      this.deptList = [];
      this.$refs.form.resetFields();
    },
    submit() {
      this.$refs.form.validate(async (valid, errors) => {
        this.showFormErr(errors);
        if (!valid) return;
        this.saving = true;
        const { is_assign, manage_section_ids, ...args } = this.form;
        let check_ids = this.filterChecks(manage_section_ids);

        let form = {
          ...args,
          manage_section_id: is_assign ? check_ids.join() : "*"
        };
        this.saving = false;
        await this.$service.user.manage(form).finally(() => {
          this.saving = false;
        });
        this.$message.success("操作成功");
        this.$emit("confirm");
        this.close();
      });
    },

    // 部门
    async getDeptList(biz_id) {
      this.deptList = [];
      if (!biz_id) return;
      const data = await this.$service.dept.list({
        parent_id: 0,
        is_store: 0,
        biz_id
      });
      this.deptList = data;
      this.treeExpand();
      return data;
    },
    // 门店
    async getShopList(biz_id) {
      this.deptList = [];
      const data = await this.getBizRefShop(biz_id);
      this.deptList = data;
      this.treeExpand();
      return data;
    },
    treeCheckChange(data, { checkedKeys }) {
      this.form.manage_section_ids = checkedKeys;
      this.$refs.form.validateField("manage_section_ids");
    },
    //节点被展开时触发的事件
    treeExpand() {
      //因为该函数执行在renderContent函数之前，所以得加定时
      setTimeout(() => {
        this.changeCss();
      }, 10);
    },
    //点击修改添加样式
    changeCss() {
      let levelName = document.getElementsByClassName("foo"); // levelname是上面的最底层节点的名字
      for (let i = 0; i < levelName.length; i++) {
        let ele = levelName[i].parentNode;
        addClass(ele, "need-float");
        addClass(ele.parentNode, "need-float-parent");
      }
    },
    //树节点的内容区的渲染 Function
    renderContent(h, { node }) {
      let classname = "";
      // 由于项目中有三级菜单也有四级级菜单，就要在此做出判断
      if (node.level === 3) {
        classname = "foo ellipsis";
      }
      if (node.level === 2 && node.childNodes.length === 0) {
        classname = "foo ellipsis";
      }
      return h("p", { class: classname }, node.label);
    }
  }
};
</script>
<style lang="scss" scoped>
.bmw {
  ::v-deep .el-form-item__label {
    display: flex;

    div {
      display: flex;
    }
  }
}

::v-deep {
  .el-dialog__body {
    max-height: 70vh;
    overflow: auto;
  }

  .mobile-tree {
    .need-float {
      width: 100% !important;
    }
  }

  .el-tree {
    margin: 12px 0;

    .need-float {
      float: left;
      width: 30%;
      background-color: #fff !important;
    }

    &-node {

      /*display: inline-block;*/
      &__content::before {
        content: "";
        padding-left: 10px;
      }

      .el-checkbox__input {
        margin-right: 6px;
      }
    }
  }
}
</style>
